package com.rede.didiok.sms.event;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rede.didiok.common.domainEvent.DomainEvent;
import com.rede.didiok.common.domainEvent.EntityType;
import com.rede.didiok.common.dto.pay.PayOrderDto;
import com.rede.didiok.common.enums.OrderStatusEnum;
import com.rede.didiok.common.feign.WebFeignClient;
import com.rede.didiok.sms.event.annotation.EventType;
import com.rede.didiok.sms.event.service.AbstractEventHandler;

/**
 * 关注事件处理器
 */
@Slf4j
@Component
@EventType({EntityType.ORDER})
public class OrderEventHandler extends AbstractEventHandler {

    @Resource
    private WebFeignClient webFeignClient;

    @Override
    public void doEventHandler(DomainEvent domainEvent) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        PayOrderDto payOrder = objectMapper.convertValue(domainEvent.getEntity(), PayOrderDto.class);
        switch (domainEvent.getEventAction()) {
            case ORDER_PAY_SUCCESS: {
                this.orderPaySuccess(payOrder);
            }
            break;
            case ORDER_CREATE_SUCCESS: {
                this.orderCreateSuccess(payOrder);
            }
            break;
            case ORDER_CANCEL_SUCCESS: {
                this.orderCancelSuccess(payOrder);
            }
            break;
        }
    }

    /**
     * 订单支付成功
     *
     * @param payOrder
     */
    public void orderCancelSuccess(PayOrderDto payOrder) {

        // 判断订单是否活动发起人取消
        if (OrderStatusEnum.OrganizerCancel.equals(payOrder.getOrderStatus()) || OrderStatusEnum.Cancelling.equals(payOrder.getOrderStatus())) {
            // 通过订单发送通知
            userFeignClient.sendNoticeByCancelOrder(payOrder);
        }


    }

    /**
     * 订单支付成功
     *
     * @param payOrder
     */
    public void orderPaySuccess(PayOrderDto payOrder) {

        // 判断订单是否完成
        if (!OrderStatusEnum.PaySuccess.equals(payOrder.getOrderStatus())) {
            return;
        }
//        // 判断是否是现金支付
//        if (PayTypeEnum.CASH_PAY.getType() != payOrder.getPayType()) {
//            return;
//        }

        // 通过订单发送通知
        userFeignClient.sendNoticeByPayOrder(payOrder);

    }

    /**
     * 订单创建成功
     *
     * @param payOrder
     */
    public void orderCreateSuccess(PayOrderDto payOrder) {
        log.info("[orderCreateSuccess] 订单事件暂未实现");
    }


}
